<script setup lang="ts">
import { ref } from 'vue'
import { timeFormat } from '@/hooks/util'
import * as imApi from '@/api/im'
import { message } from 'ant-design-vue'
import AddIM from './components/AddIM.vue'
import CorrelationList from './components/CorrelationList.vue'
import AssociatedList from './components/AssociatedList.vue'

const addIMRef = ref()
const correlationListRef = ref()
const AssociatedListRef = ref()

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
  showQuickJumper: boolean
}

const handlePageChange = (page: any, pageSize: any) => {
  // console.log(page, pageSize)
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
  showQuickJumper: true
})
let loading = ref<boolean>(false)

interface SearchParams {
  channel: number
  currentPage: number
  pageSize: number
  robotId?: string | undefined
  customerId?: string | undefined
  nickName?: string | undefined
  remark?: string | undefined
}
const searchParams = ref<SearchParams>({
  channel: 3, // 闲鱼
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref<Array<any>>([])
const columns = [
  {
    key: 'customerId',
    width: 150,
  },
  {
    title: '所属用户',
    key: 'userId',
    width: 150,
  },
  {
    title: '备注',
    key: 'remark',
    width: 150,
  },
  {
    title: '关联闲鱼账号数量',
    key: 'robotCount',
    width: 150,
    align: 'center',
  },
  {
    title: '更新时间',
    key: 'updateTime',
    width: 180,
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 90,
  },
]

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize
  searchParams.value.currentPage = pagination.value.current as number
  getList()
}
const EditRemarkSet = async (record: any) => {
  record.isRemarkShow = true
}
const getList = async () => {
  loading.value = true
  try {
    let { state, data, message: msg } = await imApi.getCustomerList(searchParams.value)
    if (state === 200) {
      data.list.forEach((item: { isRemarkShow: boolean }) => {
        item.isRemarkShow = false
      })

      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

onMounted(() => getList())

// 查询
const formRef = ref()
interface FormState {
  robotId?: string | undefined
  customerId?: string | undefined
  nickName?: string | undefined
  remark?: string | undefined
}
const formState = reactive<FormState>({})
const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.validate().then(() => {
    searchParams.value.robotId = formState.robotId || ''
    searchParams.value.customerId = formState.customerId || ''
    searchParams.value.nickName = formState.nickName || ''
    searchParams.value.remark = formState.remark || ''
    getList()
  })
}

// 重置
const reset = () => {
  formRef.value.resetFields()
  Reflect.deleteProperty(searchParams.value, 'robotId')
  Reflect.deleteProperty(searchParams.value, 'customerId')
  Reflect.deleteProperty(searchParams.value, 'nickName')
  Reflect.deleteProperty(searchParams.value, 'remark')

  getList()
}

// 修改备注
const editRemark = async (id: string, remark: string) => {
  let params = { id, remark }
  try {
    const { state, message: msg } = await imApi.editCustomerRemark(params)
    if (state === 200) {
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 删除
const del = async (id: string) => {
  try {
    let { state, message: msg } = await imApi.deleteCustomer({
      id,
    })
    if (state === 200) {
      message.success('已删除')
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 关联闲鱼账号
const correlation = (id: string) => {
  correlationListRef.value.showModal(id, 'LdleFish')
}

// 已关联闲鱼账号
const associated = (id: string) => {
  AssociatedListRef.value.showModal(id, 'LdleFish')
}

// 添加初语客服
const addIM = () => {
  addIMRef.value.showModal('LdleFish')
}
</script>

<template>
  <div class="searchBox">
    <a-form ref="formRef" layout="inline" :model="formState">
      <a-form-item label="闲鱼账号ID" name="robotId">
        <a-input v-model:value="formState.robotId" placeholder="闲鱼账号ID" />
      </a-form-item>

      <a-form-item label="客服ID" name="customerId">
        <a-input v-model:value="formState.customerId" placeholder="客服ID" />
      </a-form-item>

      <a-form-item label="昵称" name="nickName">
        <a-input v-model:value="formState.nickName" placeholder="昵称" />
      </a-form-item>

      <a-form-item label="备注" name="remark">
        <a-input v-model:value="formState.remark" placeholder="备注" />
      </a-form-item>
    </a-form>
    <a-button type="primary" style="border-radius: 6px" @click="search">
      <template #icon><SearchOutlined /></template>
      搜索
    </a-button>
    <a-button @click="reset" style="border-radius: 6px">重置</a-button>
  </div>
  <div style="margin: 5px 0">
    <a-button style="border-radius: 6px" type="primary" @click="addIM">新增初语账户</a-button>
  </div>

  <a-table
    style="overflow-x: scroll"
    :columns="columns"
    :data-source="dataSource"
    :pagination="pagination"
    :loading="loading"
    @change="changePage"
    rowKey="id"
  >
    <template #emptyText>
      <a-empty description="暂无数据" />
    </template>

    <template #headerCell="{ column }">
      <template v-if="column.key === 'customerId'">
        <span>客服ID</span>
      </template>
    </template>

    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'customerId'">
        <div style="width: 150px">{{ record.customerId }}</div>
      </template>

      <template v-else-if="column.key === 'userId'">
        <div style="width: 150px">{{ record.userId }}</div>
      </template>

      <template v-else-if="column.key === 'remark'">
        <!-- <a-input
          @blur="editRemark(record.id, record.remark)"
          v-model:value="record.remark"
          style="border: 0"
        /> -->
        <div style="display: flex; align-items: center">
          <div>备注：</div>
          <span v-if="!record.isRemarkShow">{{ record.remark }}</span>
          <a-input
            v-else
            v-model:value="record.remark"
            @blur="editRemark(record.id, record.remark)"
            style="width: 160px; border: 0"
          />
          <div>
            <EditOutlined
              @click="EditRemarkSet(record)"
              v-if="!record.isRemarkShow"
              style="margin-left: 10px; color: #1890ff"
            />
          </div>
        </div>
      </template>

      <template v-else-if="column.key === 'robotCount'">
        <a-tag color="red" style="cursor: pointer" @click="correlation(record.id)">
          {{ record.robotCount }}
        </a-tag>
      </template>

      <template v-else-if="column.key === 'updateTime'">
        <div style="width: 160px">{{ timeFormat(record.updateTime) }}</div>
      </template>

      <template v-else-if="column.key === 'createTime'">
        <div style="width: 160px">{{ timeFormat(record.createTime) }}</div>
      </template>

      <template v-else-if="column.key === 'action'">
        <div style="width: 100px; margin: 0; padding: 0">
          <a @click="correlation(record.id)">关联闲鱼账号</a>
          <br />
          <a @click="associated(record.id)">已关联闲鱼账号</a>
          <br />
          <a-popconfirm
            title="您确认要删除吗？"
            ok-text="是"
            cancel-text="否"
            @confirm="del(record.id)"
          >
            <a>删除</a>
          </a-popconfirm>
        </div>
      </template>
    </template>
  </a-table>

  <AddIM ref="addIMRef" @refresh="getList"></AddIM>
  <CorrelationList ref="correlationListRef" @refresh="getList"></CorrelationList>
  <AssociatedList ref="AssociatedListRef" @refresh="getList"></AssociatedList>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

.searchBox {
  margin-bottom: 10px;
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}
</style>
